package com.chenjun.web.controller.sys;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chenjun.common.Constant;
import com.chenjun.common.base.ResultDto;
import com.chenjun.common.bean.Pagination;
import com.chenjun.common.bean.TreeBean;
import com.chenjun.common.model.DataGridModel;
import com.chenjun.common.model.DataGridSortModel;
import com.chenjun.core.dao.generator.entity.SysArea;
import com.chenjun.core.service.sys.SysAreaService;
import com.chenjun.core.vo.sys.SysAreaDto;
import com.chenjun.web.controller.BaseController;

/**
 * 
 * @ClassName: SysAreaService 
 * @author Sean Cui
 * @date 2016-06-14 下午17:50:00 
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @version V1.0.0.0
 * @comment 该文件通过代码生成器生成，如果修改次文件后，重新生成时将覆盖修改内容，请修改生成模板或做好备份
 */

@SuppressWarnings("serial")
@Controller
@RequestMapping("sysArea")
public class SysAreaController extends BaseController {
	
	private static final Logger logger  = Logger.getLogger(SysAreaController.class);

	@Autowired
	private SysAreaService sysAreaService;

	/**
	 * 页面展示
	 * @return
	 * ModelAndView
	 */
	@RequestMapping("/list.html")
	public ModelAndView index() {
		ModelAndView mv = new ModelAndView("sysArea/list");
		//补充业务逻辑
		return mv;
	}
	
	/**
	 * 分页搜索
	 * @param datagrid
	 * @return
	 * ResultDto
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	@RequestMapping(value = "/search")
	@ResponseBody
	public ResultDto list(DataGridModel datagrid) {
		ResultDto rtDto = new ResultDto();
		datagrid.getSortBy().add(new DataGridSortModel("sort_index",DataGridSortModel.ASC));
		Pagination data = sysAreaService.doPagination(datagrid);
		rtDto.setData(data);
		return rtDto;
	}

	/**
	 * 编辑页面元素
	 * @return
	 * ResultDto
	 */
	@RequestMapping("/edit")
	@ResponseBody
	public ResultDto edit(SysAreaDto dto)  throws IllegalAccessException, InvocationTargetException{
		ResultDto rtDto = new ResultDto();
		if(StringUtils.isBlank(dto.getId())){
			dto.setDisabled("0");
			dto.setIsDelete("0");
		}
		int i = sysAreaService.createOrUpdate(SysAreaDto.getModelByDto(dto));
		if(i<=0){
			rtDto.resultError();
			rtDto.setMessage("编辑系统异常");
		}
		return rtDto;
	}

	/**
	 * 删除指定的记录
	 * @param id
	 * @return
	 * ResultDto
	 */
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public ResultDto delete(@PathVariable String id) {
		ResultDto rtDto = new ResultDto();
		
		//查询是否存在下级区域
		DataGridModel param = new DataGridModel();
		param.getParams().put("parentId", id);
		int size = sysAreaService.doCountByCondition(param);
		
		if(size > 0){
			rtDto.resultError();
			rtDto.setMessage("需先删除下级区域!");
		} else {
			SysArea sysArea = sysAreaService.get(id);
			int result = 0;
			if (sysArea != null) {
				result = sysAreaService.delete(id);
			}
			if (result <= 0) {
				rtDto.resultError();
				rtDto.setMessage("要删除的记录不存在!");
			}
		}
		
		return rtDto;
	}

	/**
	 * 根据参数获取信息
	 * @param id
	 * @return
	 * ResultDto
	 */
	@RequestMapping("/get/{id}")
	@ResponseBody
	public ResultDto get(@PathVariable String id) {
		ResultDto rtDto = new ResultDto();
		rtDto.setData(sysAreaService.get(id));
		return rtDto;
	}
	
	@RequestMapping("/getTrees")
	@ResponseBody
	public Object getAllResources(HttpServletRequest request) {
		String treeId = request.getParameter("treeId") == null ? "" : request.getParameter("treeId");
		String disable = request.getParameter("disable") == null ? "false" : request.getParameter("disable");
		Map<String, String> param = new HashMap<String, String>();
		param.put("treeId", treeId);
		param.put("disable", disable);
		List<TreeBean> tree = null;
		DataGridModel dgm = new DataGridModel();
		dgm.setStart(0);
		dgm.setRows(0);
		dgm.getSortBy().add(new DataGridSortModel("sort_index",DataGridSortModel.ASC));
		try {
			dgm.getParams().putAll(param);
			tree = findAllForTree(dgm);
		} catch (Exception e) {
			logger.error(e, e);
			tree = new ArrayList<TreeBean>(0);
		}
		return tree;
	}
	
	public List<TreeBean> findAllForTree(DataGridModel dgm) {
		List<SysArea> areas = sysAreaService.doListByCondition(dgm);
		SysArea re = new SysArea();
		re.setId("0");
		re.setName("区域管理");
		re.setParentId("-1");
		re.setSortIndex(0);
		areas.add(re);
		List<TreeBean> dtoList = modelToTreeDtoList(dgm, areas);
		return getSliderResult(dgm.getParams().get("treeId").toString(), dtoList);
	}
	
	/**
	 * 将resource 的list转化成dto的list
	 * 
	 * @param map
	 * @param areas
	 * @return List<TreeDto>
	 */
	private List<TreeBean> modelToTreeDtoList(DataGridModel dgm, List<SysArea> areas) {
		int size = areas.size();
		List<TreeBean> dtoList = new ArrayList<TreeBean>(size);
		for (int i = 0; i < size; i++) {
			TreeBean TreeDto = modelToTreeDto(dgm.getParams(), areas.get(i));
			dtoList.add(TreeDto);
		}
		return dtoList;
	}

	/**
	 * 功能dto转换树结构dto
	 * 
	 * @param map
	 * @param resource
	 * @return TreeDto
	 */
	private TreeBean modelToTreeDto(Map<String, Object> map, SysArea resource) {
		Map<String, Boolean> stateMap = new HashMap<String, Boolean>(0);
		TreeBean treeDto = new TreeBean();
		String prefix = map.get("treeId").toString();
		if (!StringUtils.isBlank(prefix)) {
			treeDto.setId(prefix + "_" + resource.getId());
		} else {
			treeDto.setId(resource.getId());
		}
		treeDto.setText(resource.getName());
		/*if ("1".equals(resource.getType())) {
			treeDto.setType(Constant.TREE_FILE_TYPE);
		}*/
		// 节点是否可选
		String isDisable = map.get("disable")+"";
		if ("true".equals(isDisable)) {
			// 全不可选
			stateMap.put(Constant.Tree.STATE_DISABLED.toString(), true);
		}
		if (!stateMap.isEmpty()) {
			treeDto.setState(stateMap);
		}
		treeDto.setFid(resource.getParentId());
		return treeDto;
	}

	public static List<TreeBean> getSliderResult(String prefix, List<TreeBean> src) {
		List<TreeBean> parents = new ArrayList<TreeBean>();
		List<TreeBean> others = new ArrayList<TreeBean>();
		// 遍历list，将父节点为0的add到list中
		// 遍历list，将父节点不为0的add到list中
		for (TreeBean dto : src) {
			TreeBean result = dto;
			if ((Constant.Tree.TOP_FID.toString()).equals(dto.getFid())) {
				result.setChildren(new ArrayList<TreeBean>());
				parents.add(result);
			} else {
				others.add(result);
			}
		}
		buildSliderTree(prefix, parents, others);
		return parents;

	}

	private static void buildSliderTree(String prefix, List<TreeBean> parents, List<TreeBean> surplus) {
		List<TreeBean> record = new ArrayList<TreeBean>();
		for (int i = 0; i < parents.size(); i++) {
			TreeBean vi = parents.get(i);
			for (int j = 0; j < surplus.size(); j++) {
				TreeBean inVi = surplus.get(j);
				String nodeId = vi.getId();
				if (!StringUtils.isBlank(prefix) && nodeId.startsWith(prefix)) {
					nodeId = nodeId.substring(prefix.length() + 1);
				}
				if (nodeId.equals(inVi.getFid())) {
					if (vi.getChildren() == null) {
						vi.setChildren(new ArrayList<TreeBean>());
					}
					vi.getChildren().add(inVi);
					record.add(inVi);
				}
			}
			surplus.removeAll(record);
		}
		if (surplus.isEmpty() || record.isEmpty()) {
			return;
		} else {
			buildSliderTree(prefix, record, surplus);
		}
	}


	@RequestMapping(value = "/{id}/gettype", method = RequestMethod.GET)
	@ResponseBody
	@RequiresPermissions("sysArea:list:base")
	public Object getTypeById(@PathVariable String id, HttpServletRequest request) {

		return sysAreaService.getTypeById(id);
	}
	
	/**
	 * 编辑时查询具体某条资源
	 * 
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/{id}/init", method = RequestMethod.GET)
	@ResponseBody
	@RequiresPermissions("sysArea:list:base")
	public Object getWhileEdit(@PathVariable String id, HttpServletRequest request) {
		SysArea sa = null;
		try {
			sa= sysAreaService.getResource(id);
		} catch (Exception e) {

		}
		return sa;
	}
}
